package com.xiaomaoguai.fcp.pre.kepler.router.rpc.server.servlet.core;


import com.xiaomaoguai.fcp.pre.kepler.router.rpc.constants.HttpConstants;
import com.xiaomaoguai.fcp.pre.kepler.router.rpc.server.servlet.response.NettyHttpServletResponse;
import org.apache.commons.javaflow.api.Continuation;
import org.springframework.core.MethodParameter;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * 
 * 在contorller return后会依次执行所有实现HandlerMethodReturnValueHandler的handleReturnValue
 * 要注意顺序,有@ResponseBody注解时不会执行
 * @author DH
 *
 */
public class ContinuationHandler implements HandlerMethodReturnValueHandler {

	@Override
	public boolean supportsReturnType(MethodParameter returnType) {

		return Continuable.class.isAssignableFrom(returnType.getParameterType());
	}

	@Override
	public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer,
								  NativeWebRequest webRequest) throws Exception {
		webRequest.setAttribute(HttpConstants.CONTINUATION, true, 0);
		mavContainer.setRequestHandled(true);
		NettyHttpServletResponse response = webRequest.getNativeResponse(NettyHttpServletResponse.class);
		Continuable a = (Continuable) returnValue;
		Continuation c = Continuation.startWith(a);
		a.setC(c);
		a.setResponse(response);
	}

}